package com.xhwl.centiotdata.suppliersystem.dnake;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.dnake.DeviceDnakeDTO;
import com.xhwl.centiotdata.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xhwl.centiotdata.pojo.constant.DnakeConstant.DEVICE_INFO_REDIS_KEY;
import static com.xhwl.centiotdata.pojo.constant.DnakeConstant.DEVICE_ONLINE_REDIS_KEY;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/12/24 16:24
 */
@Service
@Slf4j
public class DeviceDnakeHandler {

    @Resource
    private RedisUtils redisUtils;

    public List<DeviceDnakeDTO> pullDevice(Integer projectId) {
        String key = String.format(DEVICE_INFO_REDIS_KEY, projectId, "*");
        List<Object> values = redisUtils.getValues(key);
        JSONArray array = JSON.parseArray(JSON.toJSONString(values));
        log.info("获取狄耐克设备列表数据: {}", array);
        String format = String.format(DEVICE_ONLINE_REDIS_KEY, projectId, "*");
        Set<String> keys = redisUtils.getKeys(format);
        return array.stream()
                .map(e -> {
                    DeviceDnakeDTO deviceDnakeDTO = JSONObject.parseObject(JSON.toJSONString(e), DeviceDnakeDTO.class);
                    String k = String.format(DEVICE_ONLINE_REDIS_KEY, projectId, deviceDnakeDTO.getUid());
                    if (keys.contains(k)) {
                        deviceDnakeDTO.setOnline(1);
                    } else {
                        deviceDnakeDTO.setOnline(0);
                    }
                    return deviceDnakeDTO;
                })
                .collect(Collectors.toList());
    }

}
